//
//  WJCommonUtils+cache.m
//  verycloud
//
//  Created by 王军 on 2017/2/8.
//  Copyright © 2017年 王军. All rights reserved.
//
/***
 使用：

 //带code返回。带过期状态的。code = 1命中缓存
 [WJCommonUtils getCacheDetail:@"md5str"];
 //直接返回数据，过期的数据不返回
 [WJCommonUtils getCache:@"md5str"];
 //存储
 [WJCommonUtils saveCache:obj withKey:@"md5str" seconds:3600];
 
 //创建缓存key
 [WJCommonUtils createCacheKey:@"userInfo"];
 
 
 //清空缓存相关
 [WJCommonUtils getCacheSize];
 [WJCommonUtils cleanCache];
 
 ***/

#import "WJCommonUtils+cache.h"
#import "NSDictionary+MutableDeepCopy.h"
#import "WJCommonUtils+date.h"

#define kWJCommonCacheManager @"kWJCommonCacheManager"
//拼接路径
#define kCachePath  [NSHomeDirectory() stringByAppendingPathComponent:@"Library/WJCaches"]
#define kCacheFilePath(name)       [NSString stringWithFormat:@"%@/%@",kCachePath,name]


@implementation WJCommonUtils (cache)

#pragma mark -- Public
//保存1
+(void)saveWJCache:(id)obj withKey:(NSString *)key seconds:(NSInteger)seconds{
    NSString *newKey = [WJCommonUtils createCacheKey:key];
    [self saveCache:obj withKey:newKey seconds:seconds];
    
}
//保存2
+(void)saveWJCache:(id)obj withKey:(NSString *)key{
     [WJCommonUtils saveWJCache:obj withKey:key seconds:10*365*24*60*60];//默认存10年
}
//获取1
+(id)getWJCache:(NSString *)key{
    NSString *newKey = [WJCommonUtils createCacheKey:key];
    return [WJCommonUtils getCache:newKey];
}
//获取2
+(NSMutableDictionary *)getWJCacheDetail:(NSString *)key{
    NSString *newKey = [WJCommonUtils createCacheKey:key];
    return [WJCommonUtils getCacheDetail:newKey];
}
//清空缓存文件夹
+(void)cleanWJCache{
    [WJCommonUtils cleanCache];
}

+(CGFloat)getWJCacheSize{
    return [WJCommonUtils getCacheSize];
}

#pragma mark -- Private
//将东西缓存起来，seconds缓存多久 obj对象值 key：md5值，文件名
+(void)saveCache:(id)obj withKey:(NSString *)key seconds:(NSInteger)seconds{
    if (key == nil) {
        return;
    }
    NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval timeEx = nowtime + seconds;//过期时间
    NSString *exTimeStr = [NSString stringWithFormat:@"%f",timeEx];//过期时间
    NSMutableDictionary *saveItem = [NSMutableDictionary new];
    

    // [WJCommonUtils dateFormat:[NSDate new] format:@"yyyy-MM-dd HH:mm:ss"];
    saveItem[@"date"] = [WJCommonUtils dateStandardStr];//当前时间
//    saveItem[@"date"] = [WJCommonUtils dateFormat:[NSDate new] format:@"yyyy-MM-dd HH:mm:ss"];//当前时间
    saveItem[@"key"] = key;
    saveItem[@"obj"] = obj;
    saveItem[@"exTime"] = exTimeStr;
    [WJCommonUtils saveCacheValue:saveItem key:key];
}



//检查并新建缓存目录
+(void)checkCachePath{
    NSString *cachePath = kCachePath;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:cachePath]) {
        BOOL res=[fileManager createDirectoryAtPath:cachePath withIntermediateDirectories:YES attributes:nil error:nil];
        if (res) {
            NSLog(@"文件夹创建成功");
        }else{
            NSLog(@"文件夹创建失败");
        }
    }
}

//网络访问key
+(NSString *)createCacheKey:(NSString *)urlStr params:(NSDictionary *)params{
    NSString *paramsKey = [WJCommonUtils JSONStringify:params];
    NSString *keyStr = [NSString stringWithFormat:@"%@_%@_Archiver",urlStr,paramsKey];//可以加个md5
    keyStr = [WJCommonUtils md5:keyStr];
    return keyStr;
}

//字符串key
+(NSString *)createCacheKey:(NSString *)originStr{
    NSString *keyStr = [NSString stringWithFormat:@"%@_Archiver",originStr];//可以加个md5
    keyStr = [WJCommonUtils md5:keyStr];
    return keyStr;
}



//存值
+(void)saveCacheValue:(id)value key:(NSString *)key{
    if(value){
        if ([value isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dicObj =(NSDictionary *)value;
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dicObj];
            NSLog(@"%@",kCacheFilePath(key));
            BOOL bo = [data writeToFile:kCacheFilePath(key) atomically:YES];
            if (!bo) {
                NSLog(@"保存失败");
                [WJCommonUtils checkCachePath];
            }
        }
    }else{
    }
}

//取值
+(id)getCacheWithKey:(NSString *)key{
    NSString *filePath = kCacheFilePath(key);
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSDictionary *dic  = nil;
    @try {
        dic = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    @catch (NSException *exception) {
        
    }
    return dic;
}


+(float)getCacheSizeAtPath:(NSString*)folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];//从前向后枚举器
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSLog(@"fileName ==== %@",fileName);
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        NSLog(@"fileAbsolutePath ==== %@",fileAbsolutePath);
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    NSLog(@"folderSize ==== %lld",folderSize);
    return folderSize;
}

+(long long)fileSizeAtPath:(NSString*)filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//得到缓存目录下的文件名wey内容。会判断是否过期
+(id)getCache:(NSString *)key{
    NSDictionary *data = [WJCommonUtils getCacheWithKey:key];
    if(data){
        NSString *exTimeStr = data[@"exTime"];
        NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970];
        if(exTimeStr.integerValue > nowtime)
        {
            return [data[@"obj"] mutableDeepCopy];
        }
    }
    return nil;
}

//读缓存，有策略的。如果type = useOld 表示过期的数据同样返回，但是要刷新数据
+(NSMutableDictionary *)getCacheDetail:(NSString *)key{
    NSMutableDictionary *retDic = [NSMutableDictionary new];
    NSDictionary *data = [WJCommonUtils getCacheWithKey:key];
    if(data){
        NSString *exTimeStr = data[@"exTime"];
        NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970];
        if(exTimeStr.integerValue > nowtime)
        {
            NSLog(@"命中缓存");
            retDic[@"code"] = @"1";
            retDic[@"retStr"] = @"命中缓存";
            retDic[@"data"] = [data[@"obj"] mutableDeepCopy];
            return retDic;
        }else{
            NSLog(@"已过期");
            retDic[@"code"] = @"0";
            retDic[@"retStr"] = @"已过期";
            retDic[@"data"] = [data[@"obj"] mutableDeepCopy];
            return retDic;
        }
    }
    NSLog(@"没有缓存");
    retDic[@"code"] = @"-1";
    retDic[@"retStr"] = @"没有缓存";
    return retDic;
}

//清空缓存文件夹
+(void)cleanCache{
    NSString *path = kCachePath;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
}

+(CGFloat)getCacheSize{
    return [WJCommonUtils getCacheSizeAtPath:kCachePath];
}


@end
